package com.qidian.buy.service.impl;

import com.qidian.buy.entity.Customer;
import com.qidian.buy.entity.Item;
import com.qidian.buy.mapper.ItemMapper;
import com.qidian.buy.service.CartService;
import com.qidian.buy.util.JSONTools;
import com.qidian.buy.util.pojo.QDResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 郭浩
 */
@Service
public class CartServiceImpl implements CartService {
    @Value("${cart-pre}")
    private String cartPre;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public QDResult add(Customer customer, Long itemId, long spId, int quantity) {
        // 暂时先不处理规格。。。。。。
        List<Item> cart = getCart(customer);
        // 添加商品倒购物车
        boolean flag = false;
        for (Item item : cart){
            if(item.getId().equals(itemId)){
                // 修改数量
                item.setStock(item.getStock()+quantity);
                flag = true;
                break;
            }
        }
        //
        if(!flag){
            // 查询商品
            Item item = itemMapper.selectById(itemId);
            // 修改数量
            item.setStock(quantity);
            // 商品加入购物车
            cart.add(item);
        }
        // 将购物车再次写入redis
        String key = cartPre + customer.getId();
        stringRedisTemplate.opsForValue().set(key, JSONTools.object2json(cart));
        return QDResult.ok();
    }
    // 获取购物车
    private List<Item> getCart(Customer customer){
        // 准备key
        String key = cartPre + customer.getId();
        List<Item> cart = null;
        if(stringRedisTemplate.hasKey(key)){
            String cartJson = stringRedisTemplate.opsForValue().get(key);
            try{
                cart = JSONTools.json2List(cartJson,Item.class);
            }catch (Exception e){
            }
        }else{
            cart = new ArrayList<>();
        }
        return cart;
    }


    public QDResult list(Customer customer){
        return  QDResult.ok(getCart(customer));
    };
}
